<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 文件上传类
 */
class Upload extends CI_Controller {
    public function __construct(){
        parent::__construct();
        $this->load->library('request');  //自定义
        $this->load->library('response'); //自定义
        $this->load->library('session'); //公共 
        $this->load->helper(array('form', 'url'));
    }

    /**
     * [do_upload description]
     * @return [type] [description]
     */
    public function do_upload()
    {

        $reqData = $this->request->getPostData();
        log_message('info', 'upload/do_upload,data:'.json_encode($reqData)); 
        //1验证登录状态 
        $this->load->model("userModel");
        $retStatus =  $this->userModel->loginStatus($reqData);
        // var_dump($retStatus);exit; 
        if($retStatus['status']){
            $this->response->sendData($retStatus['status']);return;
        }
        $userId = $retStatus['userId'];

        $realPath = dirname(dirname(dirname(__FILE__))).'/uploads/'.date("Y-m-d");
        $pathstatus = $this->checkPath($realPath);
        $path = "uploads/".date("Y-m-d");

        $config['upload_path']      = "./$path/";
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']     = 10000;
        // $config['max_width']        = 1024;
        // $config['max_height']       = 768;
        $config['file_name']       = $userId.time().rand(1000,9999);

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('userfile')){
            $error = array('error' => $this->upload->display_errors());
            log_message('info', 'upload/do_upload,error:'.json_encode($error)); 
            $this->response->sendData(2023);return;
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            // var_dump($data);exit;
            //转相对路径
            $full_path = $data['upload_data']['full_path'];
            $position = strpos($full_path,$path);
            // echo $position;exit;
            $ret['fileUrl'] = $this->config->item('base_url') . substr($full_path, $position-1);
            $this->response->sendData(0,'',$ret);return;
        }
    }

      /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }

        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }
}
?>